
#include "SchmidtCAM.h"

uint32_t get_reg_addr( char *addr );

int main( int argc, char *argv[] ){

    if( argc != 3 ){
        printf("> (ads5294_reg_update) \n");
        printf("> usage: %s reg_addr reg_data\n", argv[0]);
        exit(0);
    }

    uint32_t reg_addr = get_reg_addr(argv[1]);
    uint32_t reg_data = atoi(argv[2]);

    // printf("> reg_addr = 0X%02X, reg_data = %d\n", reg_addr, reg_data);
    // exit(0);

    int fd = open("/dev/mem", O_RDWR | O_SYNC);
    uint *ptr1 = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, ADDR_GPIO_OUT);
    uint *gpio_reg      = ptr1;     // 0x41200000
    uint *gpio2_reg     = ptr1+2;   // 0x41200008
    
    uint *ptr2 = mmap(NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, ADDR_GPIO_IN);
    uint *gpio_in_reg   = ptr2;     // 0x41210000

    // SPI config
    SPI_CONFIG *spi_config = (SPI_CONFIG*)malloc(sizeof(SPI_CONFIG));

    setup_SPI_by_device_name( spi_config, "ads5294" );

    SPI_DATA *spi_data = (SPI_DATA*)malloc(sizeof(SPI_DATA));
    spi_data_alloc(spi_data, 1);

    spi_data_set_LS(spi_data, 
                    0, 
                    reg_addr,
                    reg_data,
                    16 );

    send_spi_data(  gpio_reg,
                    gpio2_reg,
                    gpio_in_reg,
                    spi_config, 
                    spi_data );

    free(spi_config);
    
    munmap(ptr1,10);
    munmap(ptr2,10);
    close(fd);

    printf("> (ads5294) updated reg : 0X%02X, %d\n", reg_addr, reg_data);

    return 0;
}

uint32_t get_reg_addr( char *addr ){

    printf("> extracting reg address for: %s\n", addr);

    uint32_t addr_m; 
    uint32_t i=0;

    char addr_a1[16], addr_a2[16];
    char addr_b1[16], addr_b2[16];

    for( i=0; i<256; i++ ){

        sprintf(addr_a1, "0x%02x", i);
        sprintf(addr_a2, "0x%02X", i);

        sprintf(addr_b1, "0X%02x", i);
        sprintf(addr_b2, "0X%02X", i);

        
        if( strcmp(addr, addr_a1) == 0 ){
            printf("> 0x%02x matched.\n", i);
            addr_m = i;
            break;
        }

        if( strcmp(addr, addr_a2) == 0 ){
            printf("> 0x%02X matched.\n", i);
            addr_m = i;
            break;
        }

        if( strcmp(addr, addr_b1) == 0 ){
            printf("> 0X%02x matched.\n", i);
            addr_m = i;
            break;
        }

        if( strcmp(addr, addr_b2) == 0 ){
            printf("> 0X%02X matched.\n", i);
            addr_m = i;
            break;
        }
    }

    if( i >= 256 ){
        printf("> no reg addr matched ...\n");
        exit(0);
    }

    return addr_m;
}